package leetcode.code2156;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution2 implements IDebug {

	public String subStrHash(String s, int power, int modulo, int k, int hashValue) {
		int[] pp = new int[k];
		pp[0] = 1;
		for (int i = 1; i < k; i++) {
			pp[i] = (pp[i - 1] * power) % modulo;
		}
		char[] cs = s.toCharArray();
		int hash = 0;
		for (int i = 0; i < k; i++) {
			hash += ((cs[i] - 'a' + 1) * pp[i]);
		}
		if ((hash % modulo) == hashValue) {
			return new String(cs, 0, k);
		}
		int p = k;
		while (p < cs.length) {
			int hashl = (cs[p - k] - 'a' + 1) % modulo;
			hash -= hashl;
			hash /= power;
			hash += ((cs[p] - 'a' + 1) * pp[k - 1]);
			if (hash % modulo == hashValue) {
				return new String(cs, p - k + 1, k);
			}
			p++;
		}
		return null;
	}

	@Override
	public void debug1() {
		HelpDebug.compare("ee", this.subStrHash("leetcode", 7, 20, 2, 0));

	}

	@Override
	public void debug2() {
		HelpDebug.compare("fbx", this.subStrHash("fbxzaad", 31, 100, 3, 32));

	}

	@Override
	public void debug3() {
		HelpDebug.compare("xmmhdakfursinye", this.subStrHash("xmmhdakfursinye", 96, 45, 15, 21));

	}

	@Override
	public void debug4() {
		HelpDebug.compare("nekv", this.subStrHash("xxterzixjqrghqyeketqeynekvqhc", 15, 94, 4, 16));

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug4();
		so.debug1();
		so.debug3();
		so.debug2();
	}

}
